package cn.git.javassist.learn;

import javassist.*;

/**
 * @description: 测试
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-15 08:53:25
 */
public class HelloWrold {

    public static void main(String[] args) throws NotFoundException, CannotCompileException, IllegalAccessException, InstantiationException {
        // 构建类,true参数表示使用默认classLoader
        ClassPool pool = new ClassPool(true);
        // 插入类路径，通过类路径去搜索我们的类信息
        pool.insertClassPath(new LoaderClassPath(HelloWrold.class.getClassLoader()));

        // 构建一个新的对象
        CtClass targetClass = pool.makeClass("cn.git.javassist.test.hello");
        targetClass.addInterface(pool.get(IHelloWorld.class.getName()));

        // 构建方法
        CtClass returnType = pool.get(void.class.getName());
        String methodName = "sayHello";
        CtClass[] paramTypes = new CtClass[]{pool.get(String.class.getName())};
        CtMethod method = new CtMethod(returnType, methodName, paramTypes, targetClass);

        // 设置实现体
        String bodySrc = "{" +
                            "System.out.println(\"hello \" + $1);" +
                        "}";
        method.setBody(bodySrc);
        targetClass.addMethod(method);

        // 将class对象添加到类加载器中
        Class<?> aClass = targetClass.toClass();
        IHelloWorld helloWorld = (IHelloWorld) aClass.newInstance();
        helloWorld.sayHello("lixuchun");

    }

    public interface IHelloWorld {
        /**
         * hello
         */
        void sayHello(String name);
    }

}
